package cn.xiaolang.function.java_jvm;


import java.util.HashMap;
import java.util.Map;

/**
 * Beta Phase : Do not used for others
 *
 * @author Dean
 * @date 2023/3/21
 */
public class LocalCacheHelper {

    // PS: the size
    private static final Map<String, Object> data = new HashMap<>();

    private static final Map<String, Long> ttl = new HashMap<>();

    private static final long DEFAULT_THIRTY_MIN = 30 * 60 * 1000;

    public static void put(String key, Object value) {
        put(key, value, DEFAULT_THIRTY_MIN);
    }

    public static void put(String key, Object value, long expiry) {
        data.put(key, value);
        ttl.put(key, millis(expiry));
    }

    public static void remove(String key) {
        data.remove(key);
        ttl.remove(key);
    }

    public static Object get(String key) {
        if (isExpiry(key)) {
            remove(key);
            return null;
        } else {
            return data.get(key);
        }
    }

    private static boolean isExpiry(String key) {
        Long time = ttl.get(key);
        if (time == null) {
            return false;
        } else {
            return time <= System.currentTimeMillis();
        }
    }

    private static Long millis(long expiry) {
        return System.currentTimeMillis() + expiry;
    }
}
